package com.linkoog.devtools;

import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.extensions.PluginId;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class PluginConstants {

    public static final String PLUGIN_ID = "com.github.linkoog.DevTools";
    public static final PluginId PLUGIN_ID_IDEA = PluginId.getId(PLUGIN_ID);
    public static final String PLUGIN_NAME = "DevTools";
    public static final PluginDescriptor PLUGIN_DESCRIPTOR = PluginManager.getPluginByClass(PluginConstants.class);
    public static final Path PLUGIN_PATH = PLUGIN_DESCRIPTOR.getPluginPath();

    public static List<Path> getPluginLibJars() {
        ArrayList<Path> pluginJarFiles = new ArrayList<>();
        try {
            Files.walkFileTree(PLUGIN_PATH, new SimpleFileVisitor<Path>() {
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if(file.toString().endsWith(".jar")){
                        pluginJarFiles.add(file);
                    }
                    return FileVisitResult.CONTINUE;
                }

                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    return FileVisitResult.CONTINUE;
                }
            });
        }catch (Exception ignored){
        }

        return pluginJarFiles;
    }

    public static Path getPluginJarPath(){
        List<Path> pluginLibJars = getPluginLibJars();
        if (pluginLibJars.isEmpty()) return null;

        for (Path jarFilePath : pluginLibJars) {
            File jarFileFile = jarFilePath.toFile();
            if (! jarFileFile.exists() || jarFileFile.isDirectory()) continue;
            if (jarFileFile.getName().startsWith(PluginConstants.PLUGIN_NAME)) {
                return jarFilePath;
            }
        }
        return null;
    }





}
